<?php
namespace app\admin\service;

use app\model\User;
use app\model\UserInfo;
use app\org\Random;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class UserService extends BaseService
{
	public function __construct(User $model)
    {
        $this->model = $model;
    }

    /**
     * @param array $where
     * @param $field
     * @param int $page
     * @param int $limit
     * @param string $order
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
	public function getPageList(array $where, $field, int $page, int $limit, string $order='id desc'): array
    {
        return $this->model->where($where)->field($field)->withJoin(['withUserInfo'])->page($page, $limit)->order($order)->select()->toArray();
    }

    /**
     * @param array $where
     * @param int $page
     * @param int $limit
     * @param string $order
     * @return array
     */
    public function getWhereList(array $where, int $page, int $limit, string $order='User.id desc')
    {
        $model = $this->model;
        $obj = $model::view('User', ['id','username','phone','status','login_ip','create_time'])
            ->view('UserInfo', ['nickname','name','sex','age','birthday','qq','email','address','avatar','province','city','mood'], 'UserInfo.uid=User.id')
            ->where($where);

        $list = $obj->page($page, $limit)->order($order)->select()->toArray();
        //$sql = $model::getLastSql();print_r($sql);die;
        if(!empty($list)){
            $userInfo = new UserInfo();
            foreach ($list as $key => $item){
                $list[$key]['sex'] = $userInfo->sex[$item['sex']];
            }
        }
        $count = $obj->count();

        return compact('list', 'count');
    }

    /**
     * 获取数量
     * @param array $where
     * @return int
     * @throws DbException
     */
    public function countList(array $where = []): int
    {
        return $this->model->where($where)->count();
    }

    public function getList(array $where, $field,  string $order='id desc', array $with=[]): array
    {
        return $this->model->where($where)->field($field)->with($with)->order($order)->select()->toArray();
    }

    /**
     * @param int $id
     * @param $field
     * @return array
     */
    public function getInfo(int $id, $field = '*'): array
    {
        $map = [
            'id' => $id
        ];

        if (is_string($field)) $field = explode(',', $field);
        $info = $this->getWhereInfo($map,$field,['withUserInfo']);
        return $info;
    }

    /**
     * @param array $where
     * @param $field
     * @param array $with
     * @return array
     */
    public function getWhereInfo(array $where, $field = '*', array $with = []): array
    {
        return $this->model->where($where)->field($field)->with($with)->findOrEmpty()->toArray();
    }

    /**
     * @param $data
     * @param $id
     * @return mixed
     */
    public function saved($data,$id = 0){
        //启动事务
        return $this->model->transaction(function () use ($data, $id) {
            $userData = [
                'username' => $data['username'],
                'phone' => $data['phone'],
            ];
            $infoData = [
                'nickname' => $data['name'],
                'name' => $data['name'],
                'sex' => $data['sex'],
                'email' => $data['email'],
                'avatar' => $data['avatar'],
            ];
            $modelUserInfo = app()->make(UserInfo::class);
            if ($id) {//编辑
                $this->model->where('id',$id)->update($userData);

                $modelUserInfo->where('uid',$id)->update($infoData);
            } else {//添加
                $orgRandom = app()->make(Random::class);
                $userData['salt'] = $orgRandom::alpha();
                $userData['password'] = md5('123456' . $userData['salt']);
                $this->model->save($userData);
                $id = $this->model->id;

                $infoData['uid'] = $id;
                $modelUserInfo->save($infoData);
            }
            return $id;
        });
    }

    /**
     * 新增
     * @param $data
     * @return bool
     */
    public function add($data){
        return $this->model->save($data);
    }

    /**
     * 更新
     * @param $where
     * @param $data
     * @return User
     */
    public function edit($where,$data){
        return $this->model->where($where)->update($data);
    }

    /**
     * 删除信息
     * @param int|array $id
     * @return bool 删除状态
     */
    public function del($id){
        $modelUserInfo = app()->make(UserInfo::class);
        $where = [];
        $map = [];
        if(is_array($id)){
            $where[] = ['id','in',$id];
            $map[] = ['uid','in',$id];
        }else{
            $where[] = ['id','=',$id];
            $map[] = ['uid','=',$id];
        }
        $modelUserInfo->where($map)->delete();

        return $this->model->where($where)->delete();
    }

    /**
     * 登录用户
     * @param int $id
     * @return bool 登录状态
     */
    public function setLogin($id){
        // 更新登录信息
        $data = array(
            'login_time' => time(),
            'login_ip' => get_client_ip()
        );
		
        $where['id']=['eq',$id];
        $this->edit($where,$data);

        //设置cookie
        $auth = array(
            'id' => $id,
        );
        session('admin_user', $id);
        session('admin_user_sign', data_auth_sign($auth));
        return true;
    }

    /**
     * 注销当前用户
     * @return void
     */
    public function logout(){
        session('admin_user', null);
        session('admin_user_sign', null);
        session('admin', null);
    }

}
